package com.ebelter.nb.ui.activitys;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.GsonUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.WheelView;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.btcomlib.views.dialogs.WheelViewDialog;
import com.ebelter.btcomlib.views.dialogs.picktime2.CustomDatePicker;
import com.ebelter.nb.R;
import com.ebelter.nb.beans.BC_R;
import com.ebelter.nb.beans.BP_R;
import com.ebelter.nb.model.http.HttpResponse2;
import com.ebelter.nb.model.http.request.NbNetUtils;
import com.ebelter.nb.model.http.response.NbBaseResponse;
import com.ebelter.nb.ui.fragments.trend.Trend_Scale_Fragment;
import com.ebelter.nb.ui.fragments.trend.Trend_XueYa_Fragment;
import com.ebelter.nb.ui.view.CombinView9;
import com.ebelter.nb.utils.NbUtitls;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import static com.ebelter.btcomlib.views.dialogs.TextTipDialog.Gravity_BUTTOM;

public class TrendActivity extends NBBaseActivity implements View.OnClickListener {

    public static final String TAG = "TrendActivity";
    public static final String KEY = "TrendActivity_KEY";
    public static final String USER = "TrendActivity_User";

    public static final String Trend_XUEYA = "1";//血压
    public static final String Trend_TIZHICHENG = "2";//体脂秤

    public static final String Trend_USER_1 = "1";//体脂秤
    public static final String Trend_USER_2 = "2";//体脂秤


    public String currentModifyType;//当前用户请求的类型
    public String currentUserType;//当前用户的类型


    private ImageView top_left_iv;
    private TextView top_title_tv;
    private ImageView top_right_iv;


    private CombinView9 leftTimeCb9;
    private CombinView9 rightTime1_Cb9;
    private CombinView9 rightTime2_Cb9;

    private TextView zi_tv;//自
    private TextView zhi_tv;//至


    private int leftType = 0;//0天1周2月3年

    //dateType  1:年 2:月 3周: 4:天
    //leftType 0天1周2月3年
    private int getDateTypeByLeftType(){
        if (leftType==0){
            return 4;
        }else if (leftType==1){
            return 3;
        }else if (leftType==2){
            return 2;
        }else if (leftType==3){
            return 1;
        }
        return -1;
    }

    private int tzhyn_selectedIndex = 1;


    private long time1;
    private long time2;


    private Fragment currentFragment;


    @Override
    protected int loadLayoutById() {
        return R.layout.activity_trend;
    }


    @Override
    protected void initView() {
        super.initView();

        currentModifyType = getIntent().getStringExtra(KEY);
        currentUserType = getIntent().getStringExtra(USER);

        if (TextUtils.isEmpty(currentModifyType)||TextUtils.isEmpty(currentUserType)){
            throw new RuntimeException("参数不对异常");
        }
        FV();
        setListener();
        currentFragment = getFragmentByType();
        replaceFragment(currentFragment,R.id.trend_contain_f);

    }





    private void setListener() {
        top_left_iv.setOnClickListener(this);
        top_right_iv.setOnClickListener(this);

        leftTimeCb9.setOnClickListener(this);
        rightTime1_Cb9.setOnClickListener(this);
        rightTime2_Cb9.setOnClickListener(this);

    }

    private void FV() {
        top_left_iv=findViewById(R.id.top_left_iv);
        top_right_iv=findViewById(R.id.top_right_iv);
        top_title_tv=findViewById(R.id.m_title_tv);
        ViewUtils.setImageResource(top_right_iv,R.drawable.ic_qushi);

        leftTimeCb9=findViewById(R.id.topTime_lefttype_cb9);
        rightTime1_Cb9=findViewById(R.id.topTime_right1_cb9);
        rightTime2_Cb9=findViewById(R.id.topTime_right2_cb9);
        zi_tv=findViewById(R.id.topTime_zi_tv);
        zhi_tv=findViewById(R.id.topTime_zhi_tv);
    }





    @Override
    protected void initData() {
        super.initData();


        time1 = System.currentTimeMillis();
        time2 = time1;

        updateRightTime1();
        updateRightTime2();
        updateTopTimeLayout();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getReportData();
    }

    //更新时间1
    private void updateRightTime1(){
        if (rightTime1_Cb9!=null) {
            rightTime1_Cb9.setTitle1(getDisplayTimeByLeftType(time1,leftType));
        }
    }
    //更新时间2
    private void updateRightTime2(){
        if (rightTime2_Cb9!=null){
            rightTime2_Cb9.setTitle1(getDisplayTimeByLeftType(time2,leftType));
        }
    }

    /**
     * @param leftType 0天1周2月3年
     */
    private String getDisplayTimeByLeftType(long time,int leftType){

        if (leftType==0||leftType==1){
            return getDisTime(0,time);//"yyyy-M-d"
        }else if (leftType==2){
            return getDisTime(1,time);//"yyyy-M-d"
        }else {
            return TimeUtils.formatTime10(time);// "yyyy"
        }


    }
    //yyyy-MM-dd HH:mm:ss:SSS
    //type 0年月日 1年月 2年
    public static String getDisTime(int type,long time){
        String format="";
        String country = AppUtils.getLocalStr();
        if (TextUtils.equals(country, AppUtils.en)){//除了英文其他一律显示中文的

            if (type==0){
                format="M/d/yy";
            }else if (type==1){
                format="M/yy";
            }else if (type==2){
                format="yy";
            }

        }else {

            if (type==0){
                format="yyyy/M/d";
            }else if (type==1){
                format="yyyy/M";
            }else if (type==2){
                format="yyyy";
            }
        }

        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat=new SimpleDateFormat(format);
        return TimeUtils.formatTimeByMyselt(simpleDateFormat,time);
    }




    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id==R.id.top_left_iv){
            finish();
        }else if (id==R.id.top_right_iv){

            Intent intent = new Intent(this,HistoryActivity.class);
            intent.putExtra(HistoryActivity.KEY,currentModifyType);
            intent.putExtra(HistoryActivity.USER,currentUserType);
            startActivity(intent);

        }else if (id==R.id.topTime_lefttype_cb9){
            showTZHYNDialog();
        }else if (id==R.id.topTime_right1_cb9){
            showTimeSelectDialog1();
        }
    }


    //弹出时间选择器
    private void showTimeSelectDialog1() {

        rightTime1_Cb9.setImage1(R.drawable.ic_shangla);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String time = sdf.format(time1);
        String endTime = sdf.format(Calendar.getInstance().getTime().getTime());
        String date = time.split(" ")[0];
        CustomDatePicker datePicker= new CustomDatePicker(this,new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                LogUtils.i(TAG,time);
                time1 = TimeUtils.parseFormatter6Time(time).getTime();

                if (leftType==1){//如果此时是周

                    long t2=time1+6*24*3600000;//time1一周以后的时间
                    if (t2>System.currentTimeMillis()){
                        t2=System.currentTimeMillis();
                    }
                    time2=t2;

                }

                updateRightTime1();
                updateRightTime2();

                getReportData();


            }
        }, "1945-01-01 00:00", endTime);
        // datePicker.setSelectedCalender("1991-06-13");
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(false);
        datePicker.setDayIsLoop(true);
        datePicker.setMonIsLoop(true);

        datePicker.show(date);
        datePicker.setShowTime(leftType);
        datePicker.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (rightTime1_Cb9!=null){
                    rightTime1_Cb9.setImage1(R.drawable.ic_xiala);
                }
            }
        });
       // datePicker.setBackgroundColor(getResources().getColor(R.color.redTheme));
        datePicker.setBackgroundColor(Color.parseColor("#0176ff"));

    }

    //展示天周月年对话框
    private void showTZHYNDialog() {
        if (leftTimeCb9!=null)leftTimeCb9.setImage1(R.drawable.ic_shangla);

        WheelViewDialog wheelViewDialog = new WheelViewDialog(this);
        wheelViewDialog.setGravity(Gravity_BUTTOM);


        List<String> list=new ArrayList<>();

            list.add(getString_(R.string.tian));
            list.add(getString_(R.string.zhou));
            list.add(getString_(R.string.yue));
            list.add(getString_(R.string.nian));


        wheelViewDialog.setOffeset(1);
        wheelViewDialog.setItems(list);
        wheelViewDialog.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                Log.i(TAG, "selectedIndex: " + selectedIndex + ", item: " + item);
                tzhyn_selectedIndex = selectedIndex;
            }
        });
        wheelViewDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                Log.i(TAG, "cancel");
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                Log.i(TAG, "ok");
                dialogView.cancel();
                int newType = tzhyn_selectedIndex-1;
                if (newType!=leftType){
                    leftType=newType;

                    if (leftType==1){//0天1周2月3年
                        //说明选到周了
                        long cT=System.currentTimeMillis();//当前时间
                        if (cT-time1<24*3600000*6){
                            //说明time1在7天时间内 所以
                            time1=cT-24*3600000*6;
                        }
                        time2=time1+24*3600000*6;

                    }

                    updateTopTimeLayout();
                    updateRightTime1();
                    updateRightTime2();
                    getReportData();
                }

            }
        });

        wheelViewDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (leftTimeCb9!=null) leftTimeCb9.setImage1(R.drawable.ic_xiala);
            }
        });

        wheelViewDialog.setSelectPosition(leftType);
        wheelViewDialog.show();
        wheelViewDialog.setBackgroundColor(Color.parseColor("#0176ff"));




    }

    //更新顶部的时间布局
    private void updateTopTimeLayout() {
        if (leftType==0){
            setCb9Value(leftTimeCb9,getString_(R.string.tian));
        }else if (leftType==1){
            setCb9Value(leftTimeCb9,getString_(R.string.zhou));
        }else if (leftType==2){
            setCb9Value(leftTimeCb9,getString_(R.string.yue));
        }else if (leftType==3){
            setCb9Value(leftTimeCb9,getString_(R.string.nian));
        }
        setRightTimeLayout(leftType);

    }

    private void setCb9Value(CombinView9 cb9,String value){
        if (cb9!=null) cb9.setTitle1(value);
    }


    private void setRightTimeLayout(int leftType){
        if (leftType==0||leftType==2||leftType==3){
            ViewUtils.goneView(zi_tv);
            ViewUtils.goneView(zhi_tv);
            ViewUtils.goneView(rightTime2_Cb9);
        }else if (leftType==1){
            ViewUtils.displayView(zi_tv);
            ViewUtils.displayView(zhi_tv);
            ViewUtils.displayView(rightTime2_Cb9);
        }
    }


    //dateType  1:年 2:月 3周: 4:天

    //获取趋势数据
    private void getReportData(){
        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }
        //获取设备报表数据
        //dateType  1:年 2:月 3周: 4:天
        //param  参数值 年：2018  月2018-01 周 2018-01-01（转开始日期就行，后台自动T+7） 天 2018-01-02
     //   String authKey = MainActivity.getAuthKey();
        String authKey = NbUtitls.getLoginAuthkey();

        final int dateType = getDateTypeByLeftType();//时间类型

        final String param = getTimeParamByDateType(dateType);//根据时间类型获取时间

        //LogUtils.i(TAG,"---authKey="+authKey);
        LogUtils.i(TAG,"---dateType="+dateType+"--param="+param+"--currentUserType="+currentUserType+"--currentModifyType="+currentModifyType);

        NbNetUtils.getInstance().getTrendData(this, authKey, dateType,
                param, currentUserType, currentModifyType,
                new HttpResponse2<NbBaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestResultDesc, int requestResultCode, NbBaseResponse response, String s) {

                LogUtils.i(TAG,"--getTrendData--s = " + s);

                if (isRequestSuccess && requestResultCode == 1){
                    //说明获取成功
                    if (TextUtils.equals(currentModifyType, Trend_XUEYA)){
                        displayBpmData(s);
                    }else if (TextUtils.equals(currentModifyType, Trend_TIZHICHENG)){
                        displayScaleData(s);
                    }else {
                        LogUtils.i(TAG,"----返回来json数据异常了");
                    }
                }else {
                    //说明获取失败
                    LogUtils.i(TAG,"----获取getTrendData数据失败");
                }


            }
        });





    }
    //显示体脂秤的数据
    private void displayScaleData(String s) {
        if (currentFragment!=null&&currentFragment instanceof Trend_Scale_Fragment){
            Trend_Scale_Fragment trend_scale_fragment  = (Trend_Scale_Fragment) currentFragment;
            trend_scale_fragment.setReportData(GsonUtils.getInstance().fromJson(s, BC_R.class));
        }
    }

    //显示血压计的数据
    private void displayBpmData(String s) {
        if (currentFragment!=null&&currentFragment instanceof Trend_XueYa_Fragment){
            Trend_XueYa_Fragment trend_xueYa_fragment  = (Trend_XueYa_Fragment) currentFragment;
            trend_xueYa_fragment.setReportData(GsonUtils.getInstance().fromJson(s, BP_R.class));
        }
    }


    public Fragment getFragmentByType(){
        Fragment fragment = null;
        String title = "";
        if (TextUtils.equals(currentModifyType, Trend_XUEYA)){
            fragment = new Trend_XueYa_Fragment();
            title = getString_(R.string.xyqsh);
        } else if (TextUtils.equals(currentModifyType, Trend_TIZHICHENG)){
            title = getString_(R.string.tzhchqsh);
            fragment = new Trend_Scale_Fragment();
        }
        top_title_tv.setText(title);
        return fragment;
    }


    //dateType  1:年 2:月 3周: 4:天
    //param  参数值 年：2018  月2018-01 周 2018-01-01（转开始日期就行，后台自动T+7） 天 2018-01-02
    private String getTimeParamByDateType(int dateType) {

        String timeParam;
        if (dateType==1){
            timeParam = TimeUtils.formatTime10(time1);//yyyy
        }else if (dateType==2){
            timeParam = TimeUtils.formatTime91(time1);//yyyy-MM
        }else if (dateType==3){
            timeParam = TimeUtils.formatTime3(time1);//yyyy-MM-dd
        }else if (dateType==4){
            timeParam = TimeUtils.formatTime3(time1);//yyyy-MM-dd
        }else {
            LogUtils.i(TAG,"-------dateType = "+dateType);
            throw new IllegalArgumentException("非法参数异常");
        }
        return timeParam;
    }
}
